
/**
 * 时间转换指令大全
 * @type {{}}
 */
export const dateUtils = {}

/**
 * 获取当前日期时间
 * @returns 2023-02-02 12:00:00
 */
dateUtils.getDateTime = function () {
    let now = new Date();
    let year = now.getFullYear();
    let month = (now.getMonth() + 1).toString().padStart(2, '0');
    let day = now.getDate().toString().padStart(2, '0');
    let hour = now.getHours().toString().padStart(2, '0');
    let minute = now.getMinutes().toString().padStart(2, '0');
    let second = now.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

/**
 * 获取当前时间提交时间 20230202 120000 格式20230202120000
 */
dateUtils.getDateTimeNumber = function () {
    let now = new Date();
    let year = now.getFullYear().toString().slice(-2);
    let month = (now.getMonth() + 1).toString().padStart(2, '0');
    let day = now.getDate().toString().padStart(2, '0');
    let hour = now.getHours().toString().padStart(2, '0');
    let minute = now.getMinutes().toString().padStart(2, '0');
    let second = now.getSeconds().toString().padStart(2, '0');

    let str = `${year}${month}${day}${hour}${minute}${second}`
    console.log(str)
    return str;
}
/**
 * 获取当前日期时间 -1000毫秒
 * @returns {`${number}-${string}-${string} ${string}:${string}:${string}`} 2023-02-02 12:00:00
 */
dateUtils.getDateTimeMinus1Second = function () {
    let now = new Date();
    let prevSecond = new Date(now.getTime() - 1000);
    let year = prevSecond.getFullYear();
    let month = (prevSecond.getMonth() + 1).toString().padStart(2, '0');
    let day = prevSecond.getDate().toString().padStart(2, '0');
    let hour = prevSecond.getHours().toString().padStart(2, '0');
    let minute = prevSecond.getMinutes().toString().padStart(2, '0');
    let second = prevSecond.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

dateUtils.getDateTimeMillisecondFormat = function () {
    let now = new Date();
    let year = now.getFullYear();
    let month = (now.getMonth() + 1).toString().padStart(2, '0');
    let day = now.getDate().toString().padStart(2, '0');
    let hour = now.getHours().toString().padStart(2, '0');
    let minute = now.getMinutes().toString().padStart(2, '0');
    let second = now.getSeconds().toString().padStart(2, '0');
    let millisecond = now.getMilliseconds().toString().padStart(3, '0');
    return `${year}${month}${day}${hour}${minute}${second}${millisecond}`;
}

dateUtils.getDateTimeMillisecond = function () {
    let now = new Date();
    let year = now.getFullYear();
    let month = (now.getMonth() + 1).toString().padStart(2, '0');
    let day = now.getDate().toString().padStart(2, '0');
    let hour = now.getHours().toString().padStart(2, '0');
    let minute = now.getMinutes().toString().padStart(2, '0');
    let second = now.getSeconds().toString().padStart(2, '0');
    let millisecond = now.getMilliseconds().toString().padStart(3, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}.${millisecond}`;
}

/**
 * 获取当前 时间戳
 * @returns {string} 1000
 */
dateUtils.getCurrentTimeAsString = function () {
    const date = new Date();
    const milliseconds = date.getMilliseconds().toString().padStart(4, '0');
    return milliseconds;
}
/**
 * 获取当前 时间戳 /1000
 * @returns {number} 1682217993
 */
dateUtils.getTimestamp = function () {
    return Math.floor(Date.now() / 1000);
}

// 获取当前日期
dateUtils.getTime = function () {
    let date = new Date();
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    if (m < 10) m = `0${m}`;
    let d = date.getDate();
    if (d < 10) d = `0${d}`;
    let h = date.getHours();
    if (h < 10) h = `0${h}`;
    let ms = date.getMinutes();
    if (ms < 10) ms = `0${ms}`;
    let ss = date.getSeconds();
    if (ss < 10) ss = `0${ss}`;
    this.dats = `${y}-${m}-${d} ${h}:${ms}:${ss}`;
}

// 秒数转换
/**
 *
 * @param seconds
 * @returns {string}
 */
dateUtils.convertTime = function (seconds) {
    if (seconds <= 0) {
        return '0:00';
    }

    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;

    const formatNumber = (num) => (num < 10 ? `0${num}` : num);
    let formattedTime = '';
    if (hours > 0) {
        formattedTime += `${hours}:`;
    }
    formattedTime += `${formatNumber(minutes)}:${formatNumber(secs)}`;

    return formattedTime;
}

/**
 * 1651453681 to 2022-05-01 17:54:41
 * @param unixTimestamp
 * @returns {`${number}-${string}-${string} ${string}:${string}:${string}`}
 */
dateUtils.convertUnixToTime = function (unixTimestamp) {
    const date = new Date(unixTimestamp * 1000);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    const second = date.getSeconds().toString().padStart(2, '0');

    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}


/**
 * 16位指令转换
 */
export const hexUtils = {}


/**
 * 16进制转10进制
 * @param hex
 * @returns {number}
 */
hexUtils.convertHexTo10 = function (hex) {
    let decimalism = hex.replace(/\s/g, '');
    let res = parseInt(decimalism, 16);
    return res;
}

/**
 *计算电量
 * @param volatage
 * @returns {number}
 */

hexUtils.calPercentage = function (currentCapacity) {
    const MAX_CAPACITY = 4100;   // 满电电量（100%）
    const MIN_CAPACITY = 3000;   // 关机电量（0%）

    // 边界检查
    if (currentCapacity >= MAX_CAPACITY) return 100;
    if (currentCapacity <= MIN_CAPACITY) return 0;

    // 线性计算区间内的电量百分比[6,7](@ref)
    const percentage = Math.round(
        ((currentCapacity - MIN_CAPACITY) / (MAX_CAPACITY - MIN_CAPACITY)) * 100
    );
    return percentage;
}

hexUtils.arrayBufferToHex = function (characteristic) {
    if (!characteristic || !characteristic.value) {
        console.warn('arrayBufferToHex: characteristic or characteristic.value is undefined');
        return '';
    }
    try {
        return Array.prototype.map.call(new Uint8Array(characteristic.value), x => ('00' + x
            .toString(16)).slice(-2)).join('');
    } catch (error) {
        console.error('arrayBufferToHex error:', error);
        return '';
    }
}

hexUtils.generateDateString = function () {
    const fixedModel = '01';
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    return `${fixedModel}${year}${month}${day}${hours}${minutes}${seconds}`;
}


// 偏移Key
hexUtils.XOR_KEY = 0xA5;
hexUtils.SN_LENGTH = 16;


// 获取加密buffer
hexUtils.encryptBufferSN = function (sn) {
    // if (typeof sn !== 'string' || sn.length !== hexUtils.SN_LENGTH) {
    //     throw new Error("SN码必须为16位字符串");
    // }

    const buffer = new Uint8Array(hexUtils.SN_LENGTH);
    for (let i = 0; i < hexUtils.SN_LENGTH; i++) {
        const charCode = sn.charCodeAt(i);
        buffer[i] = charCode ^ hexUtils.XOR_KEY; // 正确使用数字密钥
    }
    return buffer;
}

// 不需要解密SN
hexUtils.notEncryptSN = function (sn) {
    // if (typeof sn !== 'string' || sn.length !== hexUtils.SN_LENGTH) {
    //     throw new Error("SN码必须为16位字符串");
    // }

    const buffer = new Uint8Array(hexUtils.SN_LENGTH);
    for (let i = 0; i < hexUtils.SN_LENGTH; i++) {
        const charCode = sn.charCodeAt(i);
        buffer[i] = charCode
    }
    return buffer;
}


// 解密SN函数
hexUtils.decryptSN = function (encryptedBytes) {
    // if (!(encryptedBytes instanceof Uint8Array) || encryptedBytes.length !== hexUtils.SN_LENGTH) {
    //     throw new Error("输入数据无效");
    // }
    return Array.from(encryptedBytes, byte =>
        String.fromCharCode(byte ^ hexUtils.XOR_KEY) // 直接转换不验证字符类型
    ).join('');
}
